package com.freedy.dataStructure.sort;

import java.util.Arrays;


/**
 * @author Freedy
 * @date 2021/3/20 15:24
 */
public class RadixSort {

    public static void main(String[] args) {
        //20个随机数
        int[] arr = {368, 93, 284, 507, 204, 620, 331, 573, 910, 977,
                711, 305, 825, 438, 698, 49, 868, 241, 598, 737};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        int[][] bucket = new int[10][arr.length];
        int[] bucketIndex = new int[10];//表示每个桶所放入的数据个数
        int max = Integer.MIN_VALUE;
        for (int k : arr) {
            if (max < Integer.toString(k).length()) {
                max = Integer.toString(k).length();
            }
        }

        for (int k = 0; k < max; k++) {
            for (int ele : arr) {
                int digit = ele % 10;
                if (k != 0) digit = (ele / (int)(Math.pow(10,k))) % 10;
                bucket[digit][bucketIndex[digit]] = ele;
                bucketIndex[digit]++;
            }
            int index = 0;
            for (int i = 0; i < bucketIndex.length; i++) {
                if (bucketIndex[i] != 0) {
                    for (int j = 0; j < bucketIndex[i]; j++) {
                        arr[index] = bucket[i][j];
                        index++;
                    }
                }
            }
            bucketIndex = new int[10];//清空桶
        }

    }

}
